import { Form, Input, Modal, notification, Radio, Select, Tree, TreeProps } from 'antd';
import React, { useEffect, useState } from 'react';

import menuService from '@/api/services/security/menuService';
import operationService from '@/api/services/security/operationService';
import permissionService from '@/api/services/security/permissionService';
import { hasPermission } from '@/utils/permission';

import { Menu, Module, Permission } from '#/entity';
import { MenuType } from '#/enum';

export type PermissionModalProps = {
  formValue: Permission;
  title: string;
  show: boolean;
  onOk: VoidFunction;
  onCancel: VoidFunction;
};

export default function PermissionModal({
  title,
  show,
  formValue,
  onOk,
  onCancel,
}: PermissionModalProps) {
  const [form] = Form.useForm();
  const [modules, setModules] = useState<Module[]>([]);
  const [menus, setMenus] = useState<Menu[]>([]);
  const [selectedPermission, setSelectedPermission] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  useEffect(() => {
    operationService.moduleList({ page: 1, take: 100 }).then((res) => {
      setModules(res.data);
      form.setFieldsValue({ ...formValue });
      form.setFieldValue('module', formValue.module?.module);
    });
    menuService.menuList({}).then((res) => {
      setMenus(res);
    });
    setCheckedKeys(
      formValue.rules.map((item) => {
        console.log(item.name + (item.type === MenuType.BUTTON));
        if (item.type === MenuType.BUTTON) {
          console.log(`要${item.name}`);
          return item.id!;
        }
        return 0;
      }),
    );
  }, [form, formValue]);

  const onFinish = (values: any) => {
    if (formValue.id) {
      values.menuIds = selectedPermission;
      permissionService.updatePermission(formValue.id, values).then(() => {
        notification.success({ message: '修改成功' });
        onOk();
      });
    } else {
      values.menuIds = selectedPermission;
      permissionService.createPermission(values).then(() => {
        notification.success({ message: '新增成功' });
        onOk();
      });
    }
  };

  const onMenuCheck = (checked: React.Key[], e: any) => {
    const arr3: React.Key[] = Array.from(new Set([...checked]));
    setCheckedKeys(checked);
    setSelectedPermission(arr3);
  };

  const onExpand: TreeProps['onExpand'] = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };
  /* eslint-disable-next-line react/no-unstable-nested-components */
  return (
    <Modal
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{
        autoFocus: true,
        htmlType: 'submit',
        disabled: !hasPermission('SECURITY:PERMISSION:UPDATE') && formValue.id !== undefined,
      }}
      modalRender={(dom) => (
        <Form
          initialValues={formValue}
          form={form}
          onFinish={onFinish}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          layout="horizontal"
        >
          {dom}
        </Form>
      )}
    >
      <Form.Item<Permission> label="名称" name="name" rules={[{ required: true }, { max: 30 }]}>
        <Input />
      </Form.Item>
      <Form.Item<Permission> label="模块" name="module" rules={[{ required: true }]}>
        <Select options={modules} fieldNames={{ label: 'name', value: 'module' }} />
      </Form.Item>
      <Form.Item<Permission> label="是否只读" name="isImmutable" rules={[{ required: true }]}>
        <Radio.Group optionType="button" buttonStyle="solid">
          <Radio value> 是 </Radio>
          <Radio value={false}> 否 </Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item<Permission> label="权限" name="rules" required>
        <Tree
          checkable
          onCheck={onMenuCheck}
          checkedKeys={checkedKeys}
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          fieldNames={{
            key: 'id',
            children: 'children',
            title: 'name',
          }}
          treeData={menus}
        />
      </Form.Item>
    </Modal>
  );
}
